<template>
  <el-dialog class="public-dialog" title="拆分订单" width="80%" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div style="height: 80vh">
      <div class="text-[14px] text-[#3a4259] leading-[20px] mb-[24px] flex">
        <span v-for="item in orderConfig" :key="item.label" class="flex-1"> {{ item.label }}：{{ orderInfo[item.field] || "-" }} </span>
      </div>
      <div class="flex items-center justify-between mb-[10px]">
        <div class="flex item-center">
          <FormTitle title="商品信息" style="margin-bottom: 0" />
          <el-button type="primary" v-if="isAssembles" @click="handleAssemblesSplit" class="ml-[8px]">按子SKU拆分</el-button>
        </div>
        <div class="flex item-center">
          <el-button type="primary" @click="handleProductSplit"> 按选中的商品拆分 </el-button>
          <el-button type="primary" class="ml-[8px]">按SKU物流属性拆分</el-button>
        </div>
      </div>
      <!-- :span-method="mergeRowMethod" -->
      <vxe-table class="split-table" ref="tableRef" :data="tableData" :round="true" maxHeight="400" border>
        <vxe-column type="checkbox" width="50"></vxe-column>
        <vxe-column field="order_item_id" title="编号" width="130"></vxe-column>
        <vxe-column title="图片" width="84">
          <template #default="{ row }">
            <el-image :src="row.main_img" class="w-[68px] h-[68px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
              <template #error>
                <img src="~@/assets/images/null-img.png" alt="" />
              </template>
            </el-image>
          </template>
        </vxe-column>
        <vxe-column field="origin_num" title="SKU 自定义SKU" width="180">
          <template #header>
            <div>
              <div>SKU</div>
              <div>自定义SKU</div>
            </div>
          </template>
          <template #default="{ row }">
            <p>{{ row.sku }}</p>
            <p>{{ row.custom_sku }}</p>
          </template>
        </vxe-column>
        <vxe-column title="产品名称" field="sku_cn_title" minWidth="156">
          <template #default="{ row }">
            <el-tooltip class="box-item" effect="dark" placement="top">
              <template #content>
                <div style="max-width: 300px">{{ row.sku_cn_title }}</div>
              </template>
              <div class="sku-title">{{ row.sku_cn_title }}</div>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column title="物流属性" field="shipping_logistics_attr" width="72"> </vxe-column>
        <vxe-column title="订单数量" field="quantity" width="72"></vxe-column>
        <vxe-column title="拆分数量" width="76">
          <template #default="{ row }">
            <el-input-number style="width: 100%" v-model="row.split" placeholder="" :max="row.quantity" :controls="false" :min="0"></el-input-number>
          </template>
        </vxe-column>
        <vxe-column title="销售总价" field="original_amount" width="72"> </vxe-column>
        <vxe-column title="可用库存" field="available_stock" width="72"> </vxe-column>
        <vxe-column title="重量/体积" width="100" field="todo">
          <template #default="{ row }">
            <p>{{ row.gross_weight_g * row.quantity || "-" }} g</p>
            <p>{{ row.volume * row.quantity || "-" }} cm³</p>
            <!-- <p>{{ row.packing_weight_g || '-' }} g</p>
            <p>{{ row.volume || '-' }} cm³</p> -->
          </template>
        </vxe-column>
      </vxe-table>

      <div class="mt-[24px]" v-for="(item, index) in splitData" :key="`${index}${item.id}`">
        <div class="text-[16px] text-[#0a1431] leading-[20px] mb-[8px]">
          子订单{{ index + 1 }}
          <el-checkbox v-if="platform == 'ebay'" v-model="item.at_orange_union_create_order" @change="unionCreateChange(index)" true-value="1" false-value="0">
            使用“ebay"平台在橙联仓库建单
          </el-checkbox>
        </div>
        <vxe-table class="split-table" :data="item.list" :round="true" maxHeight="300">
          <vxe-column field="order_item_id" title="编号" width="130"></vxe-column>
          <vxe-column title="图片" width="84">
            <template #default="{ row }">
              <el-image :src="row.main_img" width="150" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
                <template #error>
                  <img src="~@/assets/images/null-img.png" alt="" />
                </template>
              </el-image>
            </template>
          </vxe-column>
          <vxe-column field="origin_num" title="SKU 自定义SKU" width="180">
            <template #header>
              <div>
                <div>SKU</div>
                <div>自定义SKU</div>
              </div>
            </template>
            <template #default="{ row }">
              <p>{{ row.sku }}</p>
              <p>{{ row.custom_sku }}</p>
            </template>
          </vxe-column>
          <vxe-column title="产品名称" field="sku_cn_title" minWidth="156">
            <template #default="{ row }">
              <el-tooltip class="box-item" effect="dark" placement="top">
                <template #content>
                  <div style="max-width: 300px">{{ row.sku_cn_title }}</div>
                </template>
                <div class="sku-title">{{ row.sku_cn_title }}</div>
              </el-tooltip>
            </template>
          </vxe-column>
          <vxe-column title="物流属性" field="shipping_logistics_attr" width="72"> </vxe-column>
          <vxe-column title="订单数量" field="quantity" width="72"></vxe-column>
          <vxe-column title="销售总价" field="original_amount" width="72">
            <template #default="{ row }">
              <p>{{ row.original_price * row.quantity || "-" }}</p>
            </template>
          </vxe-column>
          <vxe-column title="可用库存" field="available_stock" width="72"> </vxe-column>
          <vxe-column title="重量/体积" field="todo" width="100">
            <template #default="{ row }">
              <p>{{ row.gross_weight_g * row.quantity || "-" }} g</p>
              <p>{{ row.volume * row.quantity || "-" }} cm³</p>
              <!-- <p>{{ row.packing_weight_g || '-' }} g</p>
              <p>{{ row.volume || '-' }} cm³</p> -->
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>

    <template #footer center>
      <div class="flex justify-center py-[10px]">
        <el-button @click="handleClose(false)" :disabled="loading"> 取消 </el-button>
        <el-button type="primary" @click="handleReset" :disabled="loading"> 重新拆分 </el-button>
        <el-button type="primary" @click="handleSplit" :loading="loading"> 确认拆分 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import FormTitle from "@/components/XForm/FormTitle"
import { watch } from "vue"
import api from "../../api"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  data: { type: Array, default: () => [] },
})
const emit = defineEmits(["update:modelValue", "refresh"])

const { proxy } = getCurrentInstance()

const orderConfig = [
  { label: "原订单", field: "order_sn" },
  { label: "平台订单", field: "platform_order_sn" },
  // { label: '支付金额', field: 'pay_total' },
  { label: "支付金额", field: "original_order_amount" },
]
const tableData = ref([])
const tableRef = ref()
const splitData = ref([])
const loading = ref(false)
let orderInfo = reactive({
  order_sn: "",
  platform_order_sn: "",
})
const isAssembleSplit = ref(false)
// watch(
//   () => props.data,
//   val => {
//     // const orderItem = val?.[0] || {}
//     // if (!val || !orderItem?.items) return
//     // orderInfo = {
//     //   order_sn: orderItem?.order_sn,
//     //   platform_order_sn: orderItem?.platform_order_sn,
//     //   amount: orderItem?.payment?.pay_amount,
//     // }
//     // tableData.value = orderItem?.items?.map(n => ({ ...n, originQuantity: n.quantity })) || []
//   }
// )

const unionCreateChange = (index) => {
  splitData.value.forEach((item) => {
    item.at_orange_union_create_order = "0"
  })
  splitData.value[index].at_orange_union_create_order = "1"
}

const platform = ref("") // 订单平台
const isAssembles = ref("") // 是否存在组合sku
watch(
  () => props.modelValue,
  (val) => {
    isAssembleSplit.value = false
    if (val) {
      const orderItem = props.data?.[0] || {}
      platform.value = orderItem.platform
      isAssembles.value = !!orderItem?.items.find((v) => v.is_assemble == 1)
      // items
      if (!props.data || !orderItem?.items) return
      orderInfo = {
        order_sn: orderItem?.order_sn,
        original_order_amount: orderItem?.original_order_amount + " " + orderItem?.original_order_currency,
        platform_order_sn: orderItem?.platform_order_sn,
        amount: orderItem?.payment?.pay_amount,
      }
      // console.log(orderInfo)
      // console.log(orderItem)
      // if(orderItem)
      // let tabData = JSON.parse(JSON.stringify(orderItem?.items))
      // let tabData = []
      // console.log(tabData)
      // orderItem?.items.forEach((item) => {
      //   // 组合sku
      //   if (item.is_assemble) {
      //     console.log("组合sku")
      //     item.assembles.forEach((v) => {
      //       tabData.push({
      //         ...v,
      //         originQuantity: v.quantity,
      //         order_item_id: item.order_item_id,
      //         is_assemble: item.is_assemble,

      //         original_amount: item.original_amount,
      //         available_stock: item.available_stock,
      //         gross_weight_g: item.gross_weight_g,
      //         quantity: v.quantity,
      //         volume: item.volume,
      //         todo: item.order_item_id,
      //       })
      //     })
      //   } else {
      //     tabData.push({ ...item, originQuantity: item.quantity })
      //   }
      // })
      // tableData.value = tabData || []
      tableData.value = orderItem?.items?.map((n) => ({ ...n, originQuantity: n.quantity })) || []
    } else {
      tableData.value = []
      splitData.value = []
    }
  }
)

const handleClose = (refresh, param) => {
  emit("update:modelValue", false)
  if (refresh) emit("refresh", param)
}

import { apiGetWarehouseInventoryList } from "@/api/public"
// 按子SKU拆分
const handleAssemblesSplit = async () => {
  // 1240515594031509
  // console.log(199)
  // console.log(tableData.value)
  // splitData.value = tableData.value.map((n) => [{ ...n }])
  // tableData.value = tableData.value.map((n) => ({
  //   ...n,
  //   quantity: 0,
  //   split: null,
  // }))
  //
  const orderItem = props.data?.[0] || {}
  if (!props.data || !orderItem?.items) return
  // }
  console.log(orderItem)
  let tabData = []
  // console.log(tabData)
  let warehouseParams = []
  orderItem?.items.forEach((item) => {
    // 组合sku
    if (item.is_assemble) {
      console.log("组合sku")
      item.assembles.forEach((v) => {
        tabData.push({
          ...v,
          originQuantity: v.quantity,
          // order_item_id: item.order_item_id,
          order_item_id: v.id,
          is_assemble: item.is_assemble,

          // original_amount: item.original_amount,
          original_amount: 0,
          available_stock: item.available_stock,
          gross_weight_g: item.gross_weight_g,
          quantity: v.quantity * item.quantity,
          volume: item.volume,
          todo: item.order_item_id,
        })
        warehouseParams.push({
          item_sku: v.sku,
          warehouse_id: props.data?.[0]?.warehouse_id,
          rowId: v.id,
        })
      })
    } else {
      tabData.push({ ...item, originQuantity: item.quantity })
    }
  })

  let warehouseRes = await apiGetWarehouseInventoryList({ data: warehouseParams })
  tabData.forEach((item) => {
    warehouseRes.data.forEach((items) => {
      if (items.rowId == item.id) {
        item.available_stock = items.inventory
      }
    })
  })

  console.log(tabData)
  tableData.value = tabData || []
  // tableData.value = orderItem?.items?.map((n) => ({ ...n, originQuantity: n.quantity })) || []
  splitData.value = []
  isAssembleSplit.value = true
}

const handleProductSplit = () => {
  const selectRows = tableRef?.value?.getCheckboxRecords()
  if (!selectRows?.length) {
    ElMessage.warning("请选择拆分的商品")
    return
  }
  const zero = selectRows.findIndex((n) => +(n.quantity || 0) < 1)
  if (zero > -1) {
    ElMessage.warning(`第${zero + 1}个商品已拆分完毕`)
    return
  }
  const _index = selectRows.findIndex((n) => !n.split || +n.split < 1)
  if (_index > -1) {
    ElMessage.warning(`请输入第${_index + 1}个商品拆分数量`)
    return
  }
  const _ = selectRows.findIndex((n) => !n.split || +n.split < 1)
  if (_index > -1) {
    ElMessage.warning(`请输入第${_index + 1}个商品拆分数量`)
    return
  }

  tableData.value = tableData.value.map((n) => ({
    ...n,
    quantity: n.quantity - (n.split || 0),
    split: null,
  }))
  splitData.value.push({ at_orange_union_create_order: 0, list: selectRows.map((n) => ({ ...n, quantity: +n.split })) })
  tableRef.value?.clearCheckboxRow()
  splitData.value.forEach((item, i) => {
    item.at_orange_union_create_order = i == 0 ? "1" : "0"
  })
}

const handleReset = () => {
  // if (!splitData.length?.length) {
  //   ElMessage.warning('请先执行订单拆分')
  //   return
  // }
  // splitData.value = []
  // tableData.value = tableData.value.map(n => ({
  //   ...n,
  //   quantity: n.originQuantity,
  //   split: null,
  // }))

  const orderItem = props.data?.[0] || {}
  if (!props.data || !orderItem?.items) return
  // }
  // let tabData = []
  // // console.log(tabData)
  // orderItem?.items.forEach((item) => {
  //   // 组合sku
  //   if (item.is_assemble) {
  //     console.log("组合sku")
  //     item.assembles.forEach((v) => {
  //       tabData.push({
  //         ...v,
  //         originQuantity: v.quantity,
  //         order_item_id: item.order_item_id,
  //         is_assemble: item.is_assemble,

  //         original_amount: item.original_amount,
  //         available_stock: item.available_stock,
  //         gross_weight_g: item.gross_weight_g,
  //         quantity: v.quantity,
  //         volume: item.volume,
  //         todo: item.order_item_id,
  //       })
  //     })
  //   } else {
  //     tabData.push({ ...item, originQuantity: item.quantity })
  //   }
  // })
  // tableData.value = tabData || []
  tableData.value = orderItem?.items?.map((n) => ({ ...n, originQuantity: n.quantity })) || []
  splitData.value = []
  isAssembleSplit.value = false
}

const handleSplit = async () => {
  // console.log(123)
  // console.log(splitData.value)
  const { id } = props.data?.[0]

  if (!splitData.value?.length) {
    ElMessage.warning("请先执行订单拆分")
    return
  }
  try {
    loading.value = true
    let splitMain = tableData.value.filter((n) => !!+n.quantity)
    splitMain = splitMain?.map((v) => {
      let data = {
        // id: v.id,
        quantity: v.quantity,
      }
      // data[v.is_assemble ? "assemble_id" : "id"] = v.id
      data[isAssembleSplit.value && v.is_assemble ? "assemble_id" : "id"] = v.id
      return data
    })
    const splitSub = splitData.value?.map((n) => {
      return {
        at_orange_union_create_order: n?.at_orange_union_create_order,
        products: n?.list?.map((v) => {
          let data = { quantity: v.quantity }
          data[isAssembleSplit.value && v.is_assemble ? "assemble_id" : "id"] = v.id
          return data
        }),
      }
    })
    // products
    // console.log(12)
    // console.log(splitData.value)
    // console.log(splitSub)
    let product = []
    if (splitMain.length) product.push({ products: splitMain })
    // splitSub.forEach((n) => product.push({ products: n }))
    splitSub.forEach((n) => product.push(n))
    // console.log(product)
    // return
    const { data = {} } = (await api.batchSplitOrder({ order_id: id, orders: product })) || {}
    proxy.confirm({
      title: "提示",
      content: "拆分成功",
      showCancelButton: false,
      tips: (
        <div class="text-[14px] text-[#6c7283] leading-[20px] mt-[8px] mb-[2px]">
          <span class="flex items-center">
            <span>原单号：</span>
            <p>{data.source}</p>
          </span>
          <div class="flex items-start">
            <span>子单号：</span>
            <div>
              {data?.targets.map((n) => (
                <p key={n}>{n}</p>
              ))}
            </div>
          </div>
        </div>
      ),
      beforeClose: async (action, instance, done) => {
        const value = `${data.source}\n${data?.targets.join("\n")}`
        // handleClose(true,{ no:{key:'order_sn',value:value, order_sn:value}})
        handleClose(true, { pay_status: 1, orderSnRange: { type: "order_sn", value: value } })
        done()
      },
    })
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
// 1240515594031509
// 通用行合并函数（将相同多列数据合并为一行）
const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
  const fields = ["order_item_id", "original_amount", "available_stock", "todo"]
  const cellValue = row[column.field]
  if ((cellValue || cellValue == 0) && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1]
    let nextRow = visibleData[_rowIndex + 1]
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 }
    } else {
      let countRowspan = 1
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex]
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.split-table {
  :deep(.vxe-cell) {
    padding: 0 8px;
  }
}
.sku-title {
  // background: pink;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden; //溢出内容隐藏
  text-overflow: ellipsis; //文本溢出部分用省略号表示
  display: -webkit-box; //特别显示模式
  -webkit-line-clamp: 3; //行数
  line-clamp: 3;
  -webkit-box-orient: vertical; //盒子中内容竖直排列
}
</style>
